package controller;

import javafx.application.Platform;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.util.Duration;
import task.ReturnResultTask;
import thread.MultiThreadScheduledService;
import thread.MultiThreadService;
import thread.MultiThreadTask;
import executor.MyThreadPoolExecutor;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author wxhntmy
 */
public class MultiThreadController {

    /**
     * 创建新线程按键
     */
    public Button createNewThreadBtn;

    /**
     * 在线程里更新UI按键
     */
    public Button refreshUIOnThreadBtn;

    /**
     * Label
     */
    public Label UIDisplayLabel;

    /**
     * 创建新线程按键（带返回结果）
     */
    public Button createNewThreadBtnCallBack;

    /**
     * 进度条
     */
    public ProgressBar progressBar;

    /**
     * 绑定进度条的Task
     */
    public Button progressBtn;

    /**
     * 通过Service创建Task
     */
    public Button createNewThreadServiceBtn;

    /**
     * 定时任务：ScheduledService
     */
    public Button ScheduledServiceBtn;

    /**
     * 线程池实例初始化
     */
    private MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor();
    /**
     * 线程池实例
     */
    private ExecutorService executorService = myThreadPoolExecutor.createNewThreadPool();


    /**
     * 创建新线程
     *
     * @param actionEvent 事件
     */
    public void createNewThreadEvent(ActionEvent actionEvent) {
        MultiThreadTask multiThreadTask = new MultiThreadTask("new task 1");

        Task<Integer> task = new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                int iterations;
                for (iterations = 0; iterations < 10; iterations++) {
                    if (isCancelled()) {
                        break;
                    }
                    System.out.println("Iteration 2: " + iterations);
                }
                return iterations;
            }
        };

        executorService.submit(multiThreadTask);
        //不建议显式创建线程，请使用线程池。
        //new Thread(multiThreadTask).start();
        executorService.submit(task);
    }

    /**
     * 在线程里更新UI
     *
     * @param actionEvent 事件
     */
    public void refreshUIOnThreadEvent(ActionEvent actionEvent) {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                Random random = new Random();
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        UIDisplayLabel.setText("随机数：" + random.nextInt(10000));
                    }
                });
                return null;
            }
        };
        executorService.submit(task);
    }

    /**
     * 创建新线程按键（带返回结果）
     *
     * @param actionEvent 事件
     */
    public void createNewThreadBtnCallBackEvent(ActionEvent actionEvent) {
        ReturnResultTask returnResultTask = new ReturnResultTask("result task");
        executorService.submit(returnResultTask);

        //等待returnResultTask执行完成
        while (!returnResultTask.isDone()) {
            ;
        }
        System.out.println("ReturnResultTask Get Results: " + returnResultTask.getResults());
    }

    /**
     * 绑定进度条的Task
     *
     * @param actionEvent 事件
     */
    public void progressEvent(ActionEvent actionEvent) {
        Task task = new Task<Void>() {
            @Override
            public Void call() {
                final int max = 100;
                for (int i = 1; i <= max; i++) {
                    if (isCancelled()) {
                        break;
                    }
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException interrupted) {
                        if (isCancelled()) {
                            break;
                        }
                    }
                    updateProgress(i, max);
                }
                return null;
            }
        };
        progressBar.progressProperty().bind(task.progressProperty());
        executorService.submit(task);
    }

    /**
     * 通过Service创建Task
     *
     * @param actionEvent 事件
     */
    public void createNewThreadServiceEvent(ActionEvent actionEvent) {

        //运行方法一
        //创建一个Service
        MultiThreadService multiThreadService = new MultiThreadService("service");
        //给Service添加Task执行成功事件
        multiThreadService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                //获取Task返回的值
                System.out.println("done! Get Return Value: " + t.getSource().getValue());
            }
        });
        multiThreadService.start();
        //可重用
        multiThreadService.restart();

        //运行方法二
        //创建Service，注入Executor依赖，并通过注入的Executor执行实际的Task
        MultiThreadService multiThreadService2 = new MultiThreadService("service 2");
        multiThreadService2.setExecutor(executorService);
        multiThreadService2.getExecutor().execute(new Task<Object>() {
            @Override
            protected Integer call() throws Exception {
                int iterations;
                for (iterations = 15; iterations < 20; iterations++) {
                    if (isCancelled()) {
                        break;
                    }
                    System.out.println("Service Task 2 Iteration: " + iterations);
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException interrupted) {
                    if (isCancelled()) {
                        updateMessage("Cancelled");
                    }
                }
                return iterations;
            }
        });
    }

    /**
     * 定时任务：ScheduledService
     * @param actionEvent 事件
     */
    public void ScheduledServiceEvent(ActionEvent actionEvent) {

        MultiThreadScheduledService multiThreadScheduledService = new MultiThreadScheduledService("ScheduledService");
        //上次运行开始和下一次运行开始之间允许的最短时间。
        multiThreadScheduledService.setPeriod(Duration.millis(1000));
        //ScheduledService 首次启动与开始运行之间的初始延迟。
        multiThreadScheduledService.setDelay(Duration.millis(100));

        //设置 ScheduledService 是否应在 Task 失败的情况下自动重新启动。
        multiThreadScheduledService.setRestartOnFailure(false);
        //ScheduledService 在简单地以 FAILED 状态结束之前可以失败的最大次数。
        //multiThreadScheduledService.setMaximumFailureCount(10);

        //给ScheduledService添加Task执行成功事件
        multiThreadScheduledService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                //获取Task返回的值
                System.out.println("done! Get Return Value: " + t.getSource().getValue());
            }
        });
        multiThreadScheduledService.start();
    }
}
